<template>
  <main-page>
    <div slot="body">
      <el-form :inline="true" :model="search" size="mini">
        <el-form-item>
          <el-button type="primary" @click="dialogFormVisible = true;">新增</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" style="width: 100%" tooltip-effect="dark">
        <el-table-column prop="id" label="角色编号"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              title="编辑"
              size="medium"
              @click="handleClick2EditById(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              title="删除"
              size="small"
              @click="handleClick2DeleteById(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-s-promotion"
              circle
              title="角色授权"
              size="small"
              @click="authThisRole(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination :listNum="listNum" @currentChange="handleCurrentChange"></pagination>

      <el-dialog title="角色管理" :visible.sync="dialogFormVisible" width="40%">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="form.roleName" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onSubmit">提交</el-button>
        </div>
      </el-dialog>

      <el-dialog title="角色授权" :visible.sync="dialogAuthFormVisible" width="40%">
        <el-tree
          ref="tree"
          node-key="id"
          :data="permissionList"
          :props="defaultProps"
          show-checkbox
        ></el-tree>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="onAuthRoleSubmit">提交</el-button>
        </div>
      </el-dialog>
    </div>
  </main-page>
</template>

<script>
import MainPage from "common/Main";
import {
  getRolesList,
  updateRolesById,
  saveRoles,
  deleteRolesById
} from "api/RolesApi";

import {
  getPermissionByParentList,
  findPermissionIdByRoleId,
  savePermissionByRoleId
} from "api/PermissionApi";

export default {
  components: {
    MainPage
  },
  name: "rolesList",
  data() {
    return {
      tableData: [],
      listNum: 1,
      search: {
        currentIndex: 1
      },
      dialogFormVisible: false,
      dialogAuthFormVisible: false,
      form: {
        id: "",
        roleName: ""
      },
      rules: {
        roleName: [
          { required: true, message: "角色名称不能为空", trigger: "blur" }
        ]
      },
      authForm: {
        roleId: "",
        permissionIds: []
      },
      permissionList: [],
      defaultProps: {
        children: "permissionVos",
        label: "permissionName"
      }
    };
  },
  methods: {
    handleCurrentChange(page) {
      this.search.currentIndex = page;
      this.getRolesList();
    },
    getRolesList() {
      getRolesList(this.search).then(res => {
        if (res) {
          this.tableData = res.datas;
          this.listNum = res.pagination.totalCount;
        }
      });
    },
    handleClick2EditById(row) {
      this.dialogFormVisible = true;
      this.$base.set2Form(this.form, row);
    },
    handleAvatarSuccess(res, file) {
      if (res.meta.success) {
        this.form.roleName = res.data[0];
      }
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.id) {
            //修改
            updateRolesById(this.form).then(res => {
              if (res) {
                this.$base.showOk();
                this.getRolesList();
                this.dialogFormVisible = false;
              }
            });
          } else {
            //保存
            saveRoles(this.form).then(res => {
              if (res) {
                this.$base.showOk();
                this.getRolesList();
                this.dialogFormVisible = false;
              }
            });
          }
        }
      });
    },
    handleClick2DeleteById(id) {
      this.$base.deleteConfirm(() => {
        deleteRolesById({ id }).then(res => {
          if (res) {
            this.$base.deleteOk();
            this.getRolesList();
          }
        });
      });
    },
    authThisRole(id) {
      this.authForm.roleId = id;
      this.dialogAuthFormVisible = true;

      //获取已经授权的permissionId
      findPermissionIdByRoleId({ roleId: id }).then(res => {
        if (res) {
          if(res.length > 0) {
            res.forEach(item => {
              this.$refs.tree.setChecked(item, true, false);
            });
          }
        }
      });
    },
    getPermissionList() {
      getPermissionByParentList({ parentId: 0 }).then(res => {
        if (res) {
          this.permissionList = res;
        }
      });
    },
    onAuthRoleSubmit() {
      const permissionIds = this.$refs.tree
        .getHalfCheckedKeys()
        .concat(this.$refs.tree.getCheckedKeys());
      
      this.authForm.permissionIds = permissionIds;

      savePermissionByRoleId(this.authForm).then(res => {
        if(res) {
          this.$base.showOk("授权成功");
        }
      })
    }
  },
  created() {
    this.getRolesList();
    this.getPermissionList();
  },
  watch: {
    dialogFormVisible(newDialogFormVisible) {
      if (!newDialogFormVisible) {
        this.$base.clearObj(this.form);
        this.$refs.form.resetFields();
      }
    },
    dialogAuthFormVisible(newDialogAuthFormVisible) {
      if (!newDialogAuthFormVisible) {
        this.$refs.tree.setCheckedKeys([]);
        this.$base.clearObj(this.authForm);
      }
    }
  }
};
</script>
<style lang="stylus" scoped></style>
